<!-- src/views/PostListView.vue -->
<template>
  <div class="post-list-container" v-loading="loading">
    <!-- 页面标题和筛选区域 -->
    <div class="page-header">
      <h1 class="page-title">帖子列表</h1>
      <div class="filter-section">
        <!-- *** 修改点 1: 美化搜索框 ***
             *** 使用 Element Plus 的 Input Group ***
        -->
        <el-input-group class="search-input-group">
          <el-input
            placeholder="搜索帖子..."
            v-model="searchParams.keyword"
            class="search-input"
            clearable
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
          />
          <el-button :icon="Search" @click="handleSearch" type="primary">搜索</el-button>
        </el-input-group>
        <!-- 排序下拉框 -->
        <el-select v-model="searchParams.sortBy" placeholder="排序方式" @change="handleSortChange">
          <el-option label="最新发布" value="createdAt" />
          <el-option label="最多回复" value="replyCount" />
          <el-option label="最多点赞" value="likeCount" />
          <el-option label="最多收藏" value="favoriteCount" />
          <el-option label="最多浏览" value="viewCount" />
        </el-select>
        <!-- 排序方向下拉框 -->
        <el-select v-model="searchParams.sortDir" placeholder="排序方向" @change="handleSortDirectionChange">
          <el-option label="降序" value="desc" />
          <el-option label="升序" value="asc" />
        </el-select>
      </div>
    </div>

    <!-- 错误提示 -->
    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      class="error-alert"
    />

    <!-- 帖子列表 - 卡片式布局 -->
    <div class="posts-grid" v-if="posts.length > 0">
      <div class="post-card" v-for="post in posts" :key="post.id">
        <div class="post-header">
          <div class="author-info">
            <!-- *** 修改点 1: 使用真实的 authorAvatarUrl ***
                 *** 注意: 确保后端 PostSummaryDto 返回了 authorAvatarUrl 字段 ***
            -->
            <el-avatar
              :size="40"
              :src="post.authorAvatarUrl || defaultAvatar"
              @click="goToUser(post.authorId)"
              class="author-avatar"
            />
            <!-- *** --- *** -->
            <div class="author-details">
              <span class="author-name" @click="goToUser(post.authorId)">{{ post.authorName }}</span>
              <span class="post-time">{{ formatDate(post.createdAt) }}</span>
            </div>
          </div>
          <div class="category-badge">
            <el-tag size="small" effect="plain">{{ post.categoryName }}</el-tag>
          </div>
        </div>

        <div class="post-content">
          <h3 class="post-title" @click="goToPost(post.id)">
            {{ post.title }}
            <el-tag v-if="post.isTop" type="danger" size="small" effect="dark" class="badge-top">置顶</el-tag>
            <el-tag v-if="post.isEssence" type="warning" size="small" effect="light" class="badge-essence">精华</el-tag>
          </h3>

          <p class="post-excerpt" v-if="post.excerpt">{{ post.excerpt }}...</p>
        </div>

        <div class="post-stats">
          <div class="stat-item">
            <el-icon><View /></el-icon>
            <span>{{ post.viewCount }}</span>
          </div>
          <div class="stat-item">
            <el-icon><ChatDotRound /></el-icon>
            <span>{{ post.replyCount }}</span>
          </div>
         <div class="stat-item">
            <el-icon><Star /></el-icon>
            <span>{{ post.likeCount }}</span>
          </div>
          <div class="stat-item">
            <el-icon><Collection /></el-icon>
            <span>{{ post.favoriteCount }}</span>
          </div>
        </div>

        <div class="post-actions">
          <el-button
            class="like-btn"
            :class="{ 'liked': post.isLikedByCurrentUser }"
            :loading="post.likeLoading"
            @click="toggleLike(post)"
          >
            <el-icon>
              <component :is="post.isLikedByCurrentUser ? 'StarFilled' : 'Star'" />
            </el-icon>
            {{ post.isLikedByCurrentUser ? '已点赞' : '点赞' }} ({{ post.likeCount }})
          </el-button>

          <el-button class="view-btn" @click="goToPost(post.id)">
            <el-icon><View /></el-icon>
            查看详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <el-empty description="暂无帖子" :image-size="200">
        <el-button type="primary" @click="fetchPosts">刷新页面</el-button>
      </el-empty>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { getPosts, likePost, unlikePost } from '@/services/postService';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import {
  Search,
  View,
  ChatDotRound,
  Star,
  Collection,
  StarFilled
} from '@element-plus/icons-vue';


const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

const loading = ref(false);
const errorMessage = ref('');
const posts = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// --- 修改点 2: 定义默认头像 ---
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'; // Element Plus 默认头像
// --- ---

// --- 修改点 3: 定义搜索和排序参数 ---
const searchParams = reactive({
  categoryId: null, // 从 props 或 route.query 获取
  keyword: '',      // 搜索关键词
  sortBy: 'createdAt', // 默认排序字段
  sortDir: 'desc'   // 默认排序方向
});

const props = defineProps({
  categoryId: {
    type: Number,
    default: null // 默认为 null，表示获取所有帖子
  }
});
// --- ---

// 格式化日期
const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm');
};

// 跳转到帖子详情页
const goToPost = (postId) => {
  router.push(`/posts/${postId}`);
};

// --- 修改点 4: 跳转到用户详情页 ---
const goToUser = (userId) => {
  router.push(`/users/${userId}`);
};
// --- ---

// --- 修改点 5: 获取帖子列表 (集成真实 API 参数) ---
const fetchPosts = async (page = 0, size = 10) => {
  loading.value = true;
  errorMessage.value = '';
  try {
    // 构造查询参数
    const params = {
      page: page, // 后端通常从 0 开始
      size: size,
      categoryId: searchParams.categoryId, // 板块筛选
      keyword: searchParams.keyword,      // 搜索关键词
      sortBy: searchParams.sortBy,        // 排序字段
      sortDir: searchParams.sortDir       // 排序方向
    };
      // 如果 props.categoryId 存在且有效，则添加到查询参数中
    if (props.categoryId) {
      params.categoryId = props.categoryId;
    }

    // 调用真实的 API 服务
    const response = await getPosts(params);
    posts.value = response.data.content || [];
    total.value = response.data.totalElements || response.data.total || 0;
    currentPage.value = page + 1; // Element UI 页码从1开始

    // 为每个帖子初始化本地加载状态
    posts.value.forEach(post => {
      post.likeLoading = false;
      // post.isLikedByCurrentUser = false; // 可以在这里初始化，但最好由后端返回
    });
  } catch (error) {
    console.error('Failed to fetch posts:', error);
    errorMessage.value = error.response?.data?.message || '获取帖子列表失败';
    ElMessage.error(errorMessage.value);
    posts.value = [];
  } finally {
    loading.value = false;
  }
};
// --- ---

// 分页变化处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchPosts(0, val); // 页大小改变时回到第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchPosts(val - 1, pageSize.value); // Element UI 页码从1开始，后端从0开始
};

// --- 修改点 6: 搜索处理 ---
const handleSearch = () => {
  currentPage.value = 1; // 搜索时回到第一页
  fetchPosts(0, pageSize.value); // 传递当前参数
};

const handleSearchClear = () => {
  searchParams.keyword = ''; // 清空搜索关键词
  handleSearch(); // 触发搜索
};
// --- ---

// --- 修改点 7: 排序处理 ---
const handleSortChange = (val) => {
  searchParams.sortBy = val;
  currentPage.value = 1; // 排序改变时回到第一页
  fetchPosts(0, pageSize.value); // 传递当前参数
};

const handleSortDirectionChange = (val) => {
  searchParams.sortDir = val;
  currentPage.value = 1; // 排序方向改变时回到第一页
  fetchPosts(0, pageSize.value); // 传递当前参数
};
// --- ---

// 处理帖子点赞/取消点赞
const toggleLike = async (post) => {
  if (!authStore.isAuthenticated) {
    router.push('/login');
    return;
  }

  post.likeLoading = true;
  try {
    if (post.isLikedByCurrentUser) {
      await unlikePost(post.id);
      post.likeCount -= 1;
      post.isLikedByCurrentUser = false;
      ElMessage.success('取消点赞成功');
    } else {
      await likePost(post.id);
      post.likeCount += 1;
      post.isLikedByCurrentUser = true;
      ElMessage.success('点赞成功');
    }
  } catch (error) {
    console.error('Like/Unlike post failed:', error);
    ElMessage.error(error.response?.data?.message || '操作失败');
  } finally {
    post.likeLoading = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  // --- 修改点 8: 从路由参数初始化 categoryId ---
  const categoryIdFromRoute = route.query.categoryId;
  if (categoryIdFromRoute) {
    searchParams.categoryId = Number(categoryIdFromRoute);
  }
  // --- ---
  fetchPosts(currentPage.value - 1, pageSize.value); // Element UI 页码从1开始，后端从0开始
});

//监听路由参数变化 (如果需要)
watch(() => route.query, (newQuery) => {
  // 根据查询参数刷新列表
  currentPage.value = 1;
  searchParams.categoryId = newQuery.categoryId ? Number(newQuery.categoryId) : null;
  searchParams.keyword = newQuery.keyword || '';
  fetchPosts(0, pageSize.value);
}, { deep: true });
</script>

<style scoped>
.post-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2f3d;
  margin: 0;
}

.filter-section {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 250px;
}

.error-alert {
  margin-bottom: 20px;
}

.posts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.post-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: all 0.3s ease;
  border: 1px solid #eaeaea;
}

.post-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* --- 修改点 9: 更新作者头像样式 ---
     *** 添加 cursor: pointer 使头像可点击 ***
*/
.author-avatar {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.author-avatar:hover {
  transform: scale(1.05);
}
/* --- --- */

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  color: #1f2f3d;
  font-size: 14px;
  cursor: pointer; /* 使用户名可点击 */
  transition: color 0.2s ease;
}

.author-name:hover {
  color: #409eff; /* Element Plus 主题色 */
}

.post-time {
  font-size: 12px;
  color: #8c8c8c;
}

.category-badge {
  margin-left: auto;
}

.post-content {
  margin-bottom: 16px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2f3d;
  margin: 0 0 12px 0;
  cursor: pointer;
  transition: color 0.2s;
  line-height: 1.4;
}

.post-title:hover {
  color: #409eff;
}

.badge-top, .badge-essence {
  margin-left: 8px;
  vertical-align: middle;
}

.post-excerpt {
  color: #5e6d82;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #8c8c8c;
  font-size: 14px;
}

.post-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
}

.like-btn.liked {
  color: #e6a23c;
  border-color: #e6a23c;
}

.view-btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* *** 修改点 2: 添加搜索框样式 *** */
/* 确保搜索框组内的元素高度一致且圆角 */
.search-input-group {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 20px; /* 圆角 */
  overflow: hidden;
  transition: border-color 0.3s ease;
  /* 确保高度一致 */
  height: 40px; /* 设置固定高度 */
}

.search-input-group:focus-within {
  border-color: #409eff; /* 获得焦点时边框变色 */
}

/* 调整搜索输入框样式 */
.search-input {
  flex: 1;
  border: none;
  outline: none;
  padding: 8px 12px;
  font-size: 14px;
  height: 100%; /* 占满父容器高度 */
  box-sizing: border-box; /* 包含 padding 和 border */
}

.search-input .el-input__inner {
  border: none;
  border-radius: 0;
  padding: 8px 12px;
  height: 100%;
}

.search-input .el-input__suffix {
  right: 12px;
}

/* 调整搜索按钮样式 */
.search-input-group .el-button {
  border-radius: 0;
  border: none;
  background-color: #409eff;
  color: white;
  padding: 8px 16px;
  font-weight: 500;
  transition: background-color 0.3s ease;
  height: 100%; /* 占满父容器高度 */
}

.search-input-group .el-button:hover {
  background-color: #66b1ff;
}

.search-input-group .el-button:active {
  background-color: #3a8ee6;
}
/* *** --- *** */

.filter-section .el-select {
  width: 150px; /* 调整下拉框宽度 */
}

/* --- 新增: 响应式设计 ---
     *** 添加针对不同屏幕尺寸的样式 ***
*/
@media (max-width: 1200px) {
  .post-list-container {
    padding: 15px;
  }
  .page-header {
    margin-bottom: 20px;
  }
  .page-title {
    font-size: 24px;
  }
  .filter-section {
    gap: 10px;
  }
  .search-input {
    width: 250px;
  }
  .posts-grid {
    gap: 15px;
  }
  .post-card {
    padding: 15px;
  }
  .post-header {
    margin-bottom: 12px;
  }
  .author-info {
    gap: 10px;
  }
  .author-details {
    gap: 4px;
  }
  .author-name {
    font-size: 13px;
  }
  .post-time {
    font-size: 11px;
  }
  .post-content {
    margin-bottom: 12px;
  }
  .post-title {
    font-size: 16px;
  }
  .post-excerpt {
    font-size: 13px;
  }
  .post-stats {
    gap: 12px;
    margin-bottom: 12px;
    padding-bottom: 12px;
  }
  .stat-item {
    font-size: 13px;
  }
  .post-actions {
    gap: 10px;
  }
}

@media (max-width: 992px) {
  .post-list-container {
    padding: 10px;
  }
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }
  .page-title {
    text-align: center;
    font-size: 22px;
  }
  .filter-section {
    justify-content: center;
    flex-wrap: wrap;
  }
  .search-input {
    width: 100%;
  }
  .posts-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 12px;
  }
  .post-card {
    padding: 12px;
  }
  .post-header {
    margin-bottom: 10px;
  }
  .author-info {
    gap: 8px;
  }
  .author-avatar {
    width: 35px;
    height: 35px;
  }
  .author-name {
    font-size: 12px;
  }
  .post-time {
    font-size: 10px;
  }
  .post-content {
    margin-bottom: 10px;
  }
  .post-title {
    font-size: 15px;
  }
  .post-excerpt {
    font-size: 12px;
  }
  .post-stats {
    gap: 10px;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
  .stat-item {
    font-size: 12px;
  }
  .post-actions {
    gap: 8px;
  }
  .like-btn, .view-btn {
    font-size: 12px;
    padding: 6px 10px;
  }
}

@media (max-width: 768px) {
  .post-list-container {
    padding: 8px;
  }
  .page-title {
    font-size: 20px;
  }
  .filter-section {
    gap: 8px;
  }
  .posts-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  .post-card {
    padding: 10px;
  }
  .post-header {
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 8px;
  }
  .author-info {
    width: 100%;
    justify-content: space-between;
    margin-bottom: 5px;
  }
  .author-avatar {
    width: 30px;
    height: 30px;
  }
  .author-name {
    font-size: 11px;
  }
  .post-time {
    font-size: 9px;
  }
  .category-badge {
    margin-left: 0;
  }
  .post-content {
    margin-bottom: 8px;
  }
  .post-title {
    font-size: 14px;
  }
  .post-excerpt {
    font-size: 11px;
  }
  .post-stats {
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 8px;
    padding-bottom: 8px;
  }
  .stat-item {
    font-size: 11px;
  }
  .post-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  .like-btn, .view-btn {
    font-size: 11px;
    padding: 5px 8px;
  }
}

@media (max-width: 576px) {
  .post-list-container {
    padding: 5px;
  }
  .page-title {
    font-size: 18px;
  }
  .filter-section {
    gap: 5px;
  }
  .posts-grid {
    gap: 8px;
  }
  .post-card {
    padding: 8px;
  }
  .author-info {
    gap: 5px;
  }
  .author-avatar {
    width: 25px;
    height: 25px;
  }
  .author-name {
    font-size: 10px;
  }
  .post-time {
    font-size: 8px;
  }
  .post-content {
    margin-bottom: 6px;
  }
  .post-title {
    font-size: 13px;
  }
  .post-excerpt {
    font-size: 10px;
  }
  .post-stats {
    gap: 6px;
    margin-bottom: 6px;
    padding-bottom: 6px;
  }
  .stat-item {
    font-size: 10px;
  }
  .post-actions {
    gap: 3px;
  }
  .like-btn, .view-btn {
    font-size: 10px;
    padding: 4px 6px;
  }
}
/* --- --- */
</style>
